package com.spring.hot;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 三数之和
 * @author Cizai
 * @since 2022/12/01 18:51
 **/
public class 三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {

        if (nums.length == 0) return Collections.emptyList();
        ArrayList<List<Integer>> result = new ArrayList<>();

        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] > 0) continue;

            if (i > 0 && nums[i] == nums[i-1]) continue;

            int left = i+1;
            int right = nums.length - 1;

            while (left < right) {
                int sum = nums[left] + nums[right] + nums[i];

                if (sum > 0){
                    right--;
                } else if (sum < 0) {
                    left++;
                }else {
                    result.add(Arrays.asList(nums[left],nums[right],nums[i]));
                    while (left < right && nums[right]==nums[right-1]) right--;
                    while (left < right && nums[left]==nums[left+1]) left++;
                    right--;
                    left++;
                }
            }
        }
        return result;
    }
}
